package com.gjr.servicebase.handlder;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.handlers.StrictFill;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 呙境仁
 * @create 2021-08-09 19:50
 * 自动填充处理类
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        this.setFieldValByName("gmtModified", new Date(), metaObject);
        this.myStrictUpdateFill(metaObject, "gmtModified", Date.class, new Date());
    }

    private <T, E extends T> MetaObjectHandler myStrictUpdateFill(MetaObject metaObject, String parameterFieldName, Class<T> parameterFieldType, E parameterFieldVal) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
        List<StrictFill<T, E>> strictFills = Collections.singletonList(StrictFill.of(parameterFieldName, parameterFieldType, parameterFieldVal));

        boolean flag = false;

        if (!flag && tableInfo.isWithUpdateFill()) {
            strictFills.forEach((i) -> {
                String fieldName = i.getFieldName();
                Class<?> fieldType = i.getFieldType();
                tableInfo.getFieldList().stream().filter((j) -> {
                    return j.getProperty().equals(fieldName) && fieldType.equals(j.getPropertyType()) && (!flag && j.isWithUpdateFill());
                }).findFirst().ifPresent((j) -> {
                    Object obj = i.getFieldVal().get();
                    if (Objects.nonNull(obj)) {
                        metaObject.setValue(fieldName, obj);
                    }
                });
            });
        }
        return this;
    }
}
